<!--
 * @Descripttion: 聊天对象
 * @Author: 银河以北
 * @Date: 2021-09-22 21:33:41
 * @LastEditors: 银河以北
 * @LastEditTime: 2021-10-09 15:43:46
-->
<template>
  <div class="list-container">
    <div class='container'>
      <!-- 头部 -->
      <div class='header'>
        <div>
          <el-icon
            class='header-icon'
            :size='20'
            @click="addUserChat"
          >
            <Plus />
          </el-icon>
        </div>
      </div>
      <!-- 分割线 -->
      <div class='divider'></div>
      <!-- 列表 -->
      <div
        class='list'
        v-if="isChat"
      >
        <div
          class='list-item'
          @mouseover='showItemClose(item)'
          @mouseleave='showCloas=0'
          @click.stop="changeChatUser(item,true)"
          :class="{'list-active':activeChatItem.id==item.id,'list-hover':item.id==showCloas}"
          v-for='(item,index) in chatList'
          :key='index'
        >
          <div class='item-info'>
            <div style="margin-right:10px">
              <el-avatar
                :size="50"
                :src="$utils.imgUrl(item.getUserInfo.avatar_url)"
              ></el-avatar>
            </div>
            <div class='title-info'>
              <p>{{item.getUserInfo.nickname}}</p>
              <p class='chat-container'> {{item.lastInfo?.content}}</p>
            </div>
          </div>
          <div class='item-time'>
            <p>
              <el-badge
                :value="item.notRead"
                :hidden='item.notRead>0?false:true'
              >
              </el-badge>
            </p>
            <p>
              {{item.lastInfo?.create_time.slice(5,16)}}
            </p>
          </div>
          <div
            class='item-close'
            :class='{"active-close":item.id==showCloas}'
          >
            <el-icon
              class='header-icon'
              @click.stop="deleteChatUserIcon(item)"
              :size='16'
            >
              <Close />
            </el-icon>
          </div>
        </div>
      </div>
      <div
        class='list'
        v-else
      >
        <div
          class='list-item'
          @mouseover='showGroupChatItemCloss(item)'
          @mouseleave='showGroupChatCloss=0'
          @click.stop="changeChatUser(item,false)"
          :class="{'list-active':activeGroupChatItem.id==item.group_chat_id,'list-hover':item.group_chat_id==showGroupChatCloss}"
          v-for="(item,index) in groupChatList"
          :key='index'
        >
          <div class='item-info'>
            <div style="margin-right:10px">
              <el-avatar
                :size="50"
                :src='groupChatAvatar'
              ></el-avatar>
            </div>
            <div class='title-info'>
              <p>{{item.groupChatName.group_chat_name}}</p>
              <p class='chat-container'> {{item.lastInfo?.content}}</p>
            </div>
            <div
              class='item-close'
              :class='{"active-close":item.id==showCloas}'
            >
              <el-icon
                class='header-icon'
                :size='16'
              >
                <Close />
              </el-icon>
            </div>
          </div>
          <div class='item-time'>
            <p>
              {{item.lastInfo?.create_time.slice(5,16)}}
            </p>
          </div>
          <div
            class='item-close'
            :class='{"active-close":item.group_chat_id==showGroupChatCloss}'
          >
            <el-icon
              class='header-icon'
              :size='16'
              @click.stop="deleteGroupChatUserIcon(item)"
            >
              <Close />
            </el-icon>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isChat?'快速发起会话':'创建/加入群聊'"
      width="30%"
      :before-close="handleClose"
    >
      <el-input
        v-model="userEmail"
        clearable
        placeholder="请输入用户注册邮箱"
        size="small"
        v-if="isChat"
      />
      <el-input
        v-model="groupChat"
        clearable
        placeholder="请输入群聊名称"
        size="small"
        @keyup.enter='saveData'
        v-else
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button
            @click="dialogVisible = false"
            size="mini"
          >取消</el-button>
          <el-button
            type="primary"
            @click="saveData"
            size="mini"
          >确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from "vue";
//svg-icon
import { Refresh, Plus, Close } from "@element-plus/icons";

import {
  getUserChatList,
  addChatUser,
  deleteChatUser,
  addNewGroupChat,
  getUserGroupChatList,
  deleteGroupChatItem,
} from "@/api/chat/index";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";

export default defineComponent({
  name: "ListContainer",
  components: {
    Refresh,
    Plus,
    Close,
  },
  props: {
    isChat: {
      type: Boolean,
      default: true,
    },
  },

  setup(props, { emit }) {
    //引入vuex
    const store = useStore();

    //页面初始化函数
    onMounted(() => {
      init();
    });

    //群聊头像
    const groupChatAvatar = require("@/assets/img/default/groupChatAvatar.png");

    //聊天数据接口
    interface ChatListData {
      id: number;
      send_id: number;
      user_id: number;
      getUserInfo: {
        id: number;
        avatar_url: string;
        nickname: string;
      };
      notRead: number;
      lastInfo: any;
      create_time?: string;
    }

    //聊天列表数据
    let chatList: Array<ChatListData> = reactive([]);

    //群聊数据接口
    interface GroupChatListData {
      user_id: number;
      group_chat_id: number;
      groupChatName: {
        group_chat_name: "string";
        user_id: number;
      };
    }

    //群聊列表数据
    let groupChatList: Array<GroupChatListData> = reactive([]);

    //当前活动的聊天对象
    interface ChatItemData {
      id: number;
      user_id: number;
      send_id: number;
      send_nickname: string;
      type: string;
    }

    //当前活动聊天实例
    let activeChatItem: ChatItemData = reactive({
      id: 0,
      user_id: 0,
      send_id: 0,
      send_nickname: "",
      type: "chat",
    });

    //当前活动群聊实例
    interface activeGroupChatItemData {
      id: 0;
      type: string;
      user_id: number;
      send_id: number;
      send_nickname: string;
    }
    let activeGroupChatItem: activeGroupChatItemData = reactive({
      id: 0,
      type: "groupChat",
      user_id: 0,
      send_id: 0,
      send_nickname: "未知群聊",
    });

    //弹出框变量
    let dialogVisible = ref<boolean>(false);

    //聊天人邮箱
    let userEmail = ref<string>("");

    //群聊名称
    let groupChat = ref<string>("");

    //初始化函数
    const init = () => {
      /* 一对一初始化 */
      if (isChat.value) {
        getUserChatList().then((res) => {
          chatList.length = 0;
          chatList.push(...res.data);
          //数据为空 终止执行
          if (!res.data[0]) {
            return;
          }
          //如果不存在初始活动值 则进行赋值
          if (activeChatItem.id == 0) {
            const { id, user_id, send_id } = res.data[0];
            activeChatItem.id = id;
            activeChatItem.user_id = user_id;
            activeChatItem.send_id = send_id;
            activeChatItem.send_nickname = res.data[0].getUserInfo.nickname;
          }
          activeChatItem.type = "chat";
          emit("getActiveChatItem", activeChatItem);
        });
      } else {
        /* 群聊初始化 */
        getUserGroupChatList().then((res) => {
          groupChatList.length = 0;
          groupChatList.push(...res.data);
          /* 活动对象赋值 */
          activeGroupChatItem.id = res.data[0]?.group_chat_id;
          activeGroupChatItem.send_nickname =
            res.data[0]?.groupChatName?.group_chat_name;
          activeChatItem.type = "groupChat";
        });
      }
    };

    //添加聊天人
    const addUserChat = () => {
      dialogVisible.value = !dialogVisible.value;
    };

    //弹出框取消
    const handleClose = () => {
      dialogVisible.value = false;
    };

    //提交数据
    const saveData = () => {
      /* 一对一 */
      if (isChat.value) {
        //验证邮箱规则
        const emailRE =
          /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        if (!emailRE.test(userEmail.value)) {
          ElMessage({
            message: "邮箱格式不正确!请重新输入。",
            type: "warning",
          });
          return;
        }
        const data = {
          userEmail: userEmail.value,
        };
        userEmail.value = "";
        addChatUser(data).then((res: any) => {
          if (res.code == 200) {
            chatList.length = 0;
            init();
            dialogVisible.value = false;
            ElMessage({
              message: "聊天添加成功",
              type: "success",
            });
          }
        });
      } else {
        /* 群聊 */
        const data = {
          groupChatName: groupChat.value,
          clientId: store.getters.getSocketClientId,
        };
        groupChat.value = "";
        addNewGroupChat(data).then((res: any) => {
          if (res.code == 200) {
            ElMessage({
              message: "群组新增成功",
              type: "success",
            });
          }
          groupChatList.length = 0;
          init();
          dialogVisible.value = false;
        });
      }
    };

    //鼠标移入变量
    let showCloas = ref<number>(0);

    //群聊鼠标移入变量
    let showGroupChatCloss = ref<number>(0);

    //鼠标移入数据
    const showItemClose = (item: any) => {
      showCloas.value = item.id;
    };

    //群聊鼠标移入数据
    const showGroupChatItemCloss = (item: any) => {
      showGroupChatCloss.value = item.group_chat_id;
    };

    //删除聊天对象
    const deleteChatUserIcon = (item: any) => {
      //发送请求
      deleteChatUser({ send_id: item.send_id }).then((res: any) => {
        if (res.code == 200) {
          showCloas.value = 0;
          let INDEX = 0;
          chatList.forEach((chatItem, index) => {
            if (chatItem.id == item.id) {
              //当前元素的下标
              INDEX = index;

              //判断要删除的是否是活动元素
              if (chatList.length == 1) {
                const data = {
                  id: -1,
                  user_id: 0,
                  send_id: 0,
                  send_nickname: "",
                  getUserInfo: {
                    nickname: "",
                  },
                  type: "chat",
                };
                changeChatUser(data, true);
                return;
              }
              if (item.id == activeChatItem.id) {
                if (index >= 1) {
                  changeChatUser(chatList[index - 1], true);
                } else {
                  changeChatUser(chatList[index + 1], true);
                }
              }
            }
          });
          chatList.splice(INDEX, 1);
          ElMessage({
            message: "聊天对象移除成功。",
            type: "success",
          });
        }
      });
    };

    //改变聊天人
    const changeChatUser = (item: any, status: boolean) => {
      //活动元素重新赋值
      if (status) {
        activeChatItem.id = item.id;
        activeChatItem.user_id = item.user_id;
        activeChatItem.send_id = item.send_id;
        activeChatItem.send_nickname = item.getUserInfo.nickname;
        activeChatItem.type = "chat";
        emit("getActiveChatItem", activeChatItem);
      } else {
        showGroupChatCloss.value = item.group_chat_id;
        activeGroupChatItem.id = item.group_chat_id;
        activeGroupChatItem.user_id = item.user_id;
        activeGroupChatItem.send_id = 0;
        activeGroupChatItem.send_nickname = item.groupChatName.group_chat_name;
        activeGroupChatItem.type = "groupChat";
        emit("getActiveChatItem", activeGroupChatItem);
      }
    };

    //改变未读数量
    const changeNotRead = (send_id: number) => {
      chatList.forEach((item) => {
        if (item.send_id == send_id) {
          item.notRead = 0;
        }
      });
    };

    //新增未读信息
    const addNotRead = (data: any) => {
      //循环找到元素 重新赋值
      chatList.forEach((item) => {
        if (item.send_id == data.getUserInfo.id) {
          item.notRead++;
          item.lastInfo.create_time = data.create_time;
          item.lastInfo.content = data.content;
        }
      });
    };

    //判断是一对一聊 还是群聊
    let isChat = ref<boolean>(true);

    //监听聊天类型改变
    watch(props, (value) => {
      isChat.value = value.isChat;
      init();
    });

    //删除群聊
    const deleteGroupChatUserIcon = (item: any) => {
      deleteGroupChatItem({ groupId: item.group_chat_id }).then((res: any) => {
        if (res.code == 200) {
          let INDEX = 0;
          groupChatList.forEach((chatItem, index) => {
            if (chatItem.group_chat_id == item.group_chat_id) {
              //当前元素的下标
              INDEX = index;
              if (groupChatList.length == 1) {
                const data = {
                  id: -1,
                  user_id: 0,
                  send_id: 0,
                  send_nickname: "",
                  type: "groupChat",
                  group_chat_id: -1,
                  groupChatName: {
                    group_chat_name: "",
                  },
                };
                changeChatUser(data, false);
                return;
              }
              if (item.group_chat_id == activeGroupChatItem.id) {
                if (index >= 1) {
                  changeChatUser(groupChatList[index - 1], false);
                } else {
                  changeChatUser(groupChatList[index + 1], false);
                }
              }
            }
          });
          groupChatList.splice(INDEX, 1);
          ElMessage({
            message: "聊天群组移除成功。",
            type: "success",
          });
        }
      });
    };

    return {
      chatList, //聊天列表

      activeChatItem, //当前活动聊天实例

      addUserChat, //添加聊天用户

      dialogVisible, //弹出框变量

      handleClose, //弹出框取消

      userEmail, //输入框变量

      saveData, //保存数据

      showItemClose, //鼠标移入事件

      showCloas, //鼠标移入变量

      deleteChatUserIcon, //删除聊天对象

      changeChatUser, //改变聊天人

      changeNotRead, //改变未读数量

      addNotRead, //新增未读信息

      isChat, //判断是一对一聊 还是群聊

      groupChat, //群聊名称

      groupChatList, //群聊列表数据

      activeGroupChatItem, //当前活动的群聊对象

      showGroupChatCloss, //群聊鼠标移入变量

      showGroupChatItemCloss, //群聊鼠标方法

      deleteGroupChatUserIcon, //删除群聊

      groupChatAvatar, //群聊头像

      init, //数据初始化
    };
  },
});
</script>

<style lang="scss" scoped>
@import "@/style/common/defaultStyle";
@import "~@/style/common/main.scss";
@import "@/style/minxin.scss";
.list-container {
  width: 300px;
  height: 100%;
  .container {
    width: 100%;
    height: 100%;
    @include listContainerStyle();
    .header {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      height: 40px;
      div {
        .header-icon {
          color: #a5b5c1;
          cursor: pointer;
          margin-right: 10px;
          border-radius: 50%;
          padding: 3px;
          transition: 0.5s;
        }
        .header-icon:hover {
          transform: rotate(360deg);
          color: #52adff;
        }
      }
    }
    .divider {
      width: 100%;
      height: 1px;
    }
    .list {
      width: 100%;
      height: calc(100% - 41px);
      &-item {
        padding: 10px 20px;
        width: calc(100% - 40px);
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        .item-info {
          display: flex;
          justify-content: flex-start;
          .title-info {
            color: $listItemTitleColor;
            .chat-container {
              color: $listItemContainerColor;
              font-size: 14px;
              margin-top: 5px;
              width: 100px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }
        .item-time {
          color: $listItemContainerColor;
          font-size: 12px;
          text-align: right;
        }
        .item-close {
          position: absolute;
          top: 5px;
          right: -20px;
          color: #73756d;
          transition: 0.3s;
        }
        .active-close {
          right: 2px;
        }
      }
      //混入公共滚动条
      @include scrollBarStyle;
    }
  }
}
</style>